<template>
  <div class="content">
    <block v-if="isExamine">
      <div class="tab_box">
        <u-tabs
          :list="headTabs"
          @click="handelHeadTab"
          :activeStyle="{
            color: '#23AC39',
            fontSize: '30rpx',
            fontWeight: 500,
          }"
          :inactiveStyle="{
            color: '#999999',
            fontSize: '30rpx',
            fontWeight: 500,
          }"
          lineColor="#23AC39"
        ></u-tabs>
      </div>
      <div class="text_box">
        <div class="text" v-if="!tabIndex">
          <p>1、付款方付款到平台;</p>
          <p>2、申请收(全/部分)款，另一方点击确认即成功收款;</p>
          <p>3、申请退(全/部分)款，另一方点击确认即成功退款;</p>
          <p>
            4、交易产生分歧影响收款或退款，由平台客服协调处理;避免因直接付款给对方，遭骗或退款难的窘境!
          </p>
          <p>建议双方合作沟通过程尽量以文字描述!</p>
        </div>
        <div class="text" v-if="tabIndex == 1">
          <p>1、正常交易 0 服务费;</p>
          <p>
            2、倘若双方产生分歧申请平台客服解决，平台将收取担保金额5%的服务费。
          </p>
        </div>
        <div class="text" v-if="tabIndex == 2">
          <p>1、平台不对该笔担保金，属于定金、尾款或其它属性进行甄别;;</p>
          <p>2、平台仅对该笔担保金的安全进行保障。</p>
        </div>
        <p class="anniu" @click="handelOpen">担保交易</p>
      </div>
      <div class="list_box">
        <div class="tab">
          <p
            v-for="item in tabs"
            :key="item.value"
            :class="curIndex === item.value && 'on'"
            @click="handleTab(item)"
          >
            {{ item.label }}
          </p>
        </div>

        <scroll-view
          class="scroll-view-v"
          scroll-y
          refresher-enabled
          :refresher-triggered="refreshing"
          @refresherrefresh="onRefresh"
          @scrolltolower="loadMore"
          lower-threshold="50"
          :scroll-with-animation="true"
          :enhanced="true"
          :enable-passive="true"
          :enable-flex="true"
          :bounces="true"
          :show-scrollbar="false"
        >
          <div class="refresh" v-if="refreshing">
            <u-loading-icon
              mode="circle"
              text="下拉刷新..."
              timing-function="linear"
            />
          </div>

          <div class="list" v-if="currentList.length > 0">
            <div class="item" v-for="item in currentList" :key="item.id">
              <div class="head">{{ $Date(item.createTime) }}</div>
              <div class="mid">
                <div>
                  <img :src="item.payerAvatar" alt="" />
                </div>
                <div>
                  <div style="color: #4ec360">
                    ￥<span style="font-size: 16px">{{ item.amount }}</span>
                  </div>
                  <div class="arrow"></div>
                  <div v-if="item.status === 0">担保中</div>
                  <div v-else-if="item.status === 1">
                    申请收款:{{ item.price }}元
                  </div>
                  <div v-else-if="item.status === 2">
                    申请退款:{{ item.refundPrice }}元
                  </div>
                  <div v-else-if="item.status === 3">
                    已收款:{{ item.price }}元
                  </div>
                  <div v-else-if="item.status === 4">
                    已退款:{{ item.refundPrice }}元
                  </div>
                </div>
                <div>
                  <img :src="item.memberUserAvatar" alt="" />
                </div>
              </div>
              <div v-if="item.remark">备注：{{ item.remark }}</div>
              <div class="b-btn">
                <div
                  v-for="btn in btnData"
                  :key="btn.label"
                  @click="handleBtn(btn, item)"
                >
                  <div class="btn" :class="btn.value" v-if="btnShow(btn, item)">
                    {{ btn.label }}
                  </div>
                </div>
              </div>
            </div>

            <div v-if="loading">
              <u-loading-icon
                mode="circle"
                text="加载中..."
                timing-function="linear"
              />
            </div>
            <div class="no-more safe-area-bottom" v-else-if="noMore">
              已经到底了
            </div>
          </div>

          <div class="no_data" v-else>
            <img src="/static/no-data.png" alt="" />
            <p>暂无相关记录</p>
          </div>
        </scroll-view>
        <div
          class="back-top safe-area-bottom"
          v-show="showBackTop"
          @click="scrollToTop"
          :style="{ bottom: safeAreaInsets.bottom + 'px' }"
        >
          <div class="icon">
            <u-icon name="arrow-upward" color="#fff" size="24" />
          </div>
        </div>
      </div>

      <!-- <div class="del-all" v-if="currentList.length > 0" @click="delAll">
        删除所有记录
      </div> -->

      <!-- <div class="float_box">
        <p>奖励</p>
        <p>规则</p>
      </div> -->
      <!-- 担保交易 -->
      <u-popup
        @close="close"
        closeOnClickOverlay
        safeAreaInsetBottom
        :round="12"
        :show="formShow"
        mode="bottom"
      >
        <form-model
          ref="formModel"
          :walletInfo="walletInfo"
          @close="close"
        ></form-model>
      </u-popup>

      <!-- 申请退款 -->
      <u-popup
        @close="closePay"
        closeOnClickOverlay
        safeAreaInsetBottom
        :round="12"
        :show="showPay"
        mode="bottom"
      >
        <form-pay ref="formPay" :payInfo="payInfo" @close="closePay" />
      </u-popup>
    </block>

    <div class="no_data" v-else>
			<img src="/static/no-data.png" alt="">
			<p>该功能即将上线！</p>
		</div>

    <!-- <c-model visible /> -->
  </div>
</template>

<script>
import { mapState } from "vuex"
import FormModel from "./components/FormModel.vue"
import FormPay from "./components/FormPay.vue"
import api from "@/api"
import { Debounce } from "@/utils/utils.js"
export default {
  components: {
    FormModel,
    FormPay,
  },
  options: {
    styleIsolation: "shared",
  },
  data() {
    return {
      noMore: false,
      loading: false,
      refreshing: false,
      showBackTop: false,
      scrollTop: 0,
      safeAreaInsets: { bottom: 0 }, // 安全区域
      lastScrollTime: 0, // 滚动时间记录
      showPay: false,
      payInfo: {},
      btnData: [
        { label: "平台客服", value: "customer" },
        { label: "申请退款", value: "refundPayment" },
        { label: "申请收款", value: "receivePayment" },
        { label: "拒绝放款", value: "refusePayment" },
        { label: "同意放款", value: "agreePayment" },
        { label: "拒绝", value: "refuse" },
        { label: "同意", value: "agree" },
      ],
      walletInfo: {},
      headTabs: [
        {
          name: "交易流程",
        },
        {
          name: "收费规则",
        },
        {
          name: "平台申明",
        },
      ],
      tabIndex: 0,
      formShow: false,
      curIndex: 1,
      tabs: [
        { label: "担保中", value: 1, count: 0 },
        { label: "已完成", value: 2, count: 0 },
      ],
      orderList: [],
      total: 0,
      params: {
        pageNo: 1,
        pageSize: 10,
        // payerId: "",
        // payerName: "",
      },
      isExamine: false, // 是否需要审核
    }
  },
  computed: {
    ...mapState({
      userName: (state) => state.user.userName,
      userId: (state) => state.user.userId,
      token: (state) => state.user.token,
      userTx: (state) => state.user.userTx,
    }),
    currentList() {
      if (this.curIndex === 1) {
        return this.orderList.filter((item) => item.status < 3)
      } else {
        return this.orderList.filter((item) => item.status > 2)
      }
    },
  },
  onPageScroll(e) {
    this.scrollTop = e.scrollTop
    // 当滚动高度超过300时显示按钮，可根据需要调整
    this.showBackTop = e.scrollTop > 300
  },
  methods: {
    async handelOpen() {
      await this.getWallet()
      this.formShow = true
    },
    delAll() {
      //删除当前列表所有记录
      const ids = this.currentList.map((item) => item.id)
      uni.showModal({
        title: "温馨提示",
        content: `确认删除所有已完成担保记录?删除后不可恢复`,
        showCancel: true,
        cancelText: "再想想",
        confirmText: "确认删除",
        success: (res) => {
          if (res.confirm) {
            api.user.del_items(ids).then((res) => {
              if (res.code == 200) {
                this.$toast("删除成功")
                this.getList()
              }
            })
          }
        },
      })
    },
    // 回到顶部
    scrollToTop() {
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 300,
      })
      this.showBackTop = false
    },
    // 获取安全区域
    getSafeArea() {
      try {
        const systemInfo = uni.getSystemInfoSync()
        this.safeAreaInsets = systemInfo.safeAreaInsets || { bottom: 0 }
      } catch (e) {
        console.error("获取安全区域失败", e)
      }
    },
    // 加载更多 - 添加节流控制
    loadMore() {
      if (this.loading || this.noMore) return
      this.getList(true)
    },
    // 下拉刷新
    onRefresh() {
      if (this.loading) return
      this.refreshing = true
      this.getList()
    },

    handleBtn(btn, item) {
      /**
       *  @status
       * 0, "未收款",
       * 1, "收款中",
       * 2, "退款中",
       * 3, "已收款",
       * 4, "已退款"
       */
      switch (btn.value) {
        case "customer":
          //客服
          this.handelCustomer(item)
          break
        case "refundPayment":
          // 申请退款
          this.handelRefund(btn, item)
          break
        case "receivePayment":
          //申请收款
          this.handelReceive(btn, item)
          break
        case "refusePayment":
          //拒绝收款
          this.handelRefusePayment(btn, item)
          break
        case "agreePayment":
          //同意收款
          this.handelAgreePayment(btn, item)
          break
        case "agree":
          //同意按钮 只有在退款中状态才会显示
          this.handelAgree(item)
          break
        case "refuse":
          //拒绝按钮 只有在退款中状态才会显示
          this.handelRefuse(item)
          break
      }
    },
    //同意放款
    handelAgreePayment(btn, item) {
      uni.showModal({
        title: "温馨提示",
        content: `对方请求放款￥${item.price}元`,
        showCancel: true,
        cancelText: "再想想",
        confirmText: "同意放款",
        success: (res) => {
          if (res.confirm) {
            api.user
              .receive_agree({ guaranteeOrderId: item.id, id: item.payOrderId })
              .then((res) => {
                if (res.code == 200) {
                  this.$toast("放款成功")
                  this.getList()
                }
              })
          }
        },
      })
    },
    //拒绝放款
    handelRefusePayment(btn, item) {
      uni.showModal({
        title: "温馨提示",
        content: `确认拒绝放款给对方吗？`,
        showCancel: true,
        cancelText: "再想想",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            api.user
              .receive_refuse({ guaranteeOrderId: item.id })
              .then((res) => {
                if (res.code == 200) {
                  this.$toast("拒绝成功")
                  this.getList()
                }
              })
          }
        },
      })
    },
    handelCustomer(item) {
      uni.showModal({
        title: "温馨提示",
        content: `确认申请客服介入，平台会收取5%的手续费?`,
        showCancel: true,
        cancelText: "再想想",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            //跳转客服
          }
        },
      })
    },
    handelRefuse(item) {
      uni.showModal({
        title: "温馨提示",
        content: `确认拒绝对方退款吗？
        (退款：${item.price}元)
        `,
        showCancel: true,
        cancelText: "再想想",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            api.user
              .refund_refuse({ guaranteeOrderId: item.id })
              .then((res) => {
                if (res.code == 200) {
                  this.$toast("拒绝成功")
                  this.getList()
                }
              })
          }
        },
      })
    },
    handelAgree(item) {
      uni.showModal({
        title: "温馨提示",
        content: `确认同意对方退款吗？
        (退款：${item.price}元)
        `,
        showCancel: true,
        cancelText: "再想想",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            api.user
              .refund_agree({ guaranteeOrderId: item.id, id: item.payOrderId })
              .then((res) => {
                if (res.code == 200) {
                  this.$toast("退款成功")
                  this.getList()
                }
              })
          }
        },
      })
    },
    handelRefund(btn, item) {
      //申请退款
      this.showPay = true
      this.payInfo = { btn: btn, row: item }
    },
    handelReceive(btn, item) {
      //申请收款
      this.showPay = true
      this.payInfo = { btn: btn, row: item }
    },
    btnShow(btn, item) {
      if (item.status > 2) {
        //已收款或者退款，所有按钮不显示
        return false
      }
      //其他显示逻辑
      switch (btn.value) {
        case "customer":
          return true
        case "refundPayment":
          console.log(this.userId)
          return this.userId === item.payer && item.status === 0
        case "receivePayment":
          return this.userId === item.memberUserId && item.status === 0
        case "refusePayment":
        case "agreePayment":
          return this.userId === item.payer && item.status === 1
        case "agree":
        case "refuse":
          return this.userId === item.memberUserId && item.status === 2
        default:
          return false
      }
    },
    //获取钱包信息  totalExpense_累计支出  totalRecharge_累计充值
    async getWallet() {
      const res = await api.wallet.get()
      this.walletInfo = res?.data
    },
    handelHeadTab(item) {
      this.tabIndex = item.index
    },
    async getList(isPage = false) {
      if (isPage) {
        this.params.pageNo++
      } else {
        this.params.pageNo = 1
      }
      this.loading = true
      const res = await api.user.guarantee_list(this.params)
      const data = res?.data?.list.map((v) => {
        v.amount = ((v.price + v.refundPrice) / 100).toFixed(2)
        v.price = v.price && (v.price / 100).toFixed(2)
        v.refundPrice = v.refundPrice && (v.refundPrice / 100).toFixed(2)
        return v
      })

      if (!isPage) {
        this.orderList = data
      } else {
        this.orderList = [...this.orderList, ...data]
      }

      this.total = res?.data?.total

      //没有更多数据了
      if (this.orderList.length >= this.total) {
        this.noMore = true
      }

      setTimeout(() => {
        this.refreshing = false
        this.loading = false
      }, 500)
    },
    handleTab(item) {
      this.curIndex = item.value
      this.getList()
    },
    closePay() {
      this.payInfo = {}
      this.$refs.formPay.resetForm()
      this.showPay = false
      this.getList()
    },
    close() {
      this.$refs.formModel.resetForm()
      this.formShow = false
      this.getList()
    },
  },
  onLoad() {
    this.getList()
  },
  async onShow(){
    await api.user.get_IOS_enable().then((res) => {
      if (res.code == 200) {
        this.isExamine = res.data
      }
    })
  }
}
</script>

<style lang="scss" scoped>
.content {
  position: relative;
  min-height: 100vh;
  background: #fff;
  .tab_box {
    background: #fff;
    /deep/ .u-tabs__wrapper__nav__item {
      // justify-content: space-around;
      padding: 0 64rpx;
    }
  }
  .text_box {
    background: #f7f7f7;
    padding-bottom: 50rpx;
    .text {
      height: 260rpx;
      padding: 30rpx 30rpx 50rpx 30rpx;
      color: #999999;
      font-size: 26rpx;
      line-height: 46rpx;
    }
  }
  .anniu {
    margin: 0 30rpx;
    height: 96rpx;
    line-height: 96rpx;
    border-radius: 100rpx;
    background: linear-gradient(270deg, #62ce73 0%, #23ac39 100%);
    text-align: center;
    color: #ffffff;
    font-size: 32rpx;
  }
  .list_box {
    padding: 45rpx 0;
    .tab {
      width: 440rpx;
      height: 56rpx;
      border-radius: 8rpx;
      background: #eeeeee;
      margin: 0 auto;
      display: flex;
      // margin-bottom: 20rpx;
      p {
        width: 50%;
        text-align: center;
        line-height: 56rpx;
        color: #999999;
        font-size: 26rpx;
        &.on {
          background: #08961f;
          color: #ffffff;
          border-radius: 4px;
        }
      }
    }
    .no_data {
      text-align: center;
      margin-top: 100rpx;
      img {
        width: 320rpx;
        height: 320rpx;
      }
      p {
        font-size: 24rpx;
        color: #999999;
        margin-top: -40rpx;
      }
    }

    .list {
      height: 100vh;
      padding: 20rpx;
      .item {
        font-size: 24rpx;
        //  box-sizing: border-box;
        padding: 20rpx;
        //  height: 200rpx;
        // background: #f7f7f7;
        border: 1px solid #eeeeee;
        border-radius: 8rpx;
        margin-bottom: 20rpx;
        .head {
          color: #999;
        }

        .mid {
          width: 100%;
          display: flex;
          align-items: center;
          justify-content: space-between;
          margin: 20rpx 0;
          > div {
            &:first-child,
            &:last-child {
              width: 100rpx;
              height: 100rpx;
              border-radius: 20rpx;
              background: #f7f7f7;
              overflow: hidden;
              img {
                width: 100%;
                height: 100%;
              }
            }
            &:nth-child(2) {
              flex: 1;
              display: flex;
              flex-direction: column;
              align-items: center;
              .arrow {
                position: relative;
                width: 85%;
                height: 10rpx;
                background: #f7f7f7;
                margin: 10rpx 0;
                &::after {
                  content: "";
                  position: absolute;
                  width: 0;
                  height: 0;
                  border-left: 20rpx solid #f7f7f7;
                  border-bottom: 20rpx solid transparent;
                  border-top: 20rpx solid transparent;
                  top: -15rpx;
                  right: 0;
                }
              }
            }
          }
        }
      }
    }
  }
  .float_box {
    position: fixed;
    right: 30rpx;
    bottom: 50rpx;
    width: 96rpx;
    height: 96rpx;
    border-radius: 100rpx;
    background: #f9fffa;
    box-shadow: 0px 0px 20rpx 0px rgba(68, 94, 150, 0.3);
    font-size: 26rpx;
    color: #08961f;
    text-align: center;
    display: flex;
    flex-direction: column;
    justify-content: center;
  }
}

.b-btn {
  display: flex;
  justify-content: flex-end;
  margin-top: 20rpx;
  .btn {
    color: #000;
    padding: 5rpx 20rpx;
    margin-left: 15rpx;
    border: 1px solid #ccc;
    border-radius: 20rpx;
  }

  .receivePayment,
  .agree,
  .agreePayment {
    background: #4ec361;
    color: #fff;
  }

  .refuse,
  .refusePayment {
    background: #ff4d4d;
    color: #fff;
  }

  .refundPayment {
    background: #f1b51c;
    color: #fff;
  }
}

.safe-area {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.safe-area-top {
  padding-top: constant(safe-area-inset-top);
  padding-top: env(safe-area-inset-top);
}

.safe-area-bottom {
  margin-bottom: constant(safe-area-inset-bottom);
  margin-bottom: env(safe-area-inset-bottom);
}

.back-top {
  position: fixed;
  right: 40rpx;

  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  .icon {
    width: 80rpx;
    height: 80rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

/* 滚动容器 */
.scroll-view-v {
  height: 100%;
  width: 100%;
  -webkit-overflow-scrolling: touch; /* iOS惯性滚动 */
  overflow-anchor: none; /* 防止滚动跳跃 */
  box-sizing: border-box;
  // padding-bottom: 100rpx;
}

.no-more {
  text-align: center;
  color: #999;
}

.del-all {
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  color: #999;
  background: #eeeeee;
  text-align: center;
  z-index: 9999;
}
.no_data{
  text-align: center;
  padding:50rpx 0;
  img{
    width: 320rpx;
    height: 320rpx;
  }
  p{
    font-size: 24rpx;
    color: #999999;
    margin-top:-40rpx;
  }
}
</style>
